package net.hzlj.platform.enterprise.utils;

import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.google.gson.GsonBuilder;
import com.orhanobut.logger.Logger;

import net.hzlj.platform.enterprise.beans.resp.RespBaseBean;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Created by Administrator on 2016/8/19 0019.
 */
public class GsonUtils {

    private static final String TAG = GsonUtils.class.getSimpleName();


    public static <T> T fromJson(String json) {
        if (!TextUtils.isEmpty(json)) {
            json = EncoderUtils.base64Decode(json);
            return JSON.parseObject(json,new TypeReference<T>(){});
        }
        return null;
    }

    public static String formatString(String json) {
        if (!TextUtils.isEmpty(json)) {
            json = EncoderUtils.base64Decode(json);
            return json;
        }else{
            json = JSON.toJSONString(new RespBaseBean());
        }
        return json;
    }


    public static RespBaseBean fromJson(String json, Class... clazz) {
        Type objectType = type(RespBaseBean.class, clazz);
        if (StringUtils.isEmpty(json)){
            return new RespBaseBean();
        }
        try{
            Logger.json(json);
            JSONObject j = JSONObject.parseObject(json);
            if (j.containsKey("values") && j.get("values") != null){
                return new GsonBuilder().create().fromJson(
                        json, objectType);
            }else {
                return new GsonBuilder().create().fromJson(
                        json, RespBaseBean.class);
            }
        }catch (Exception e){
            e.printStackTrace();
            Log.d(TAG,"响应结果解析失败",e);
        }
        return new RespBaseBean();
    }

    public static ParameterizedType type(final Class raw, final Type... args) {
        return new ParameterizedType() {
            public Type getRawType() {
                return raw;
            }

            public Type[] getActualTypeArguments() {
                return args;
            }

            public Type getOwnerType() {
                return null;
            }
        };
    }
}
